import useAsync from './useAsync';

type FetchHandler<D, ARG extends unknown[] = []> = (...args: ARG) => Promise<D>;

export default function useRequest<D, ARG extends unknown[]>(callback: FetchHandler<D, ARG>) {
    const [state, setState] = useAsync<D>();

    async function fetchHandler(...args: ARG) {
        try {
            setState({ ...state, loading: true });
            const data = await callback(...args);
            setState({ ...state, loading: false, data });
        } catch (error: unknown) {
            if (process.env.NODE_ENV !== 'production') {
                console.error(error);
            }
            setState({ ...state, loading: false, error });
        }
    }

    return {
        ...state,
        run: fetchHandler,
    };
}
